package com.cskaoyan.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.cskaoyan.service.AccountService;
import com.cskaoyan.service.UserService;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author stone
 * @date 2022/05/27 15:27
 */
@Configuration
@ComponentScan("com.cskaoyan")
public class TransactionConfiguration {

    @Bean
    public DataSourceTransactionManager platformTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/cskaoyan_db?useUnicode=true&characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        configurer.setBasePackage("com.cskaoyan.mapper");
        return configurer;
    }

    @Bean
    public TransactionProxyFactoryBean accountServiceProxy(AccountService accountService, PlatformTransactionManager transactionManager) {
        TransactionProxyFactoryBean proxyFactoryBean = new TransactionProxyFactoryBean();
        proxyFactoryBean.setTarget(accountService);
        proxyFactoryBean.setTransactionManager(transactionManager);
        // 配置方法和TransactionDefinition之间的关系
        Properties transactionAttributes = new Properties();
        transactionAttributes.put("transfer", "PROPAGATION_REQUIRED,ISOLATION_DEFAULT,timeout_5,readOnly");
        proxyFactoryBean.setTransactionAttributes(transactionAttributes);

        return proxyFactoryBean;
    }
}
